package com.zhouxiaoge.controller;

import com.zhouxiaoge.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 周明阳
 * mail:gqzmy@outlook.com
 * 时间:2018-03-20 16:45
 */
@RestController
public class MovieController {

    private final RestTemplate restTemplate;
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    public MovieController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @GetMapping("/movie/{id}")
    public ResponseEntity<User> findById(@PathVariable Long id) {
        return this.restTemplate.getForEntity("http://user-provider-1/simple/" + id, User.class);
    }

    @GetMapping("/movies")
    public List queryAll() {
        List forObject = this.restTemplate.getForObject("http://user-provider-1/simple/list", List.class);
        for (Object o : forObject) {
            LinkedHashMap hashMap = (LinkedHashMap) o;
            Object id = hashMap.get("id");
            System.out.println(id.toString());
            System.out.println(o.toString());
        }
        return forObject;
    }

    /*这样是实现访问microservice-provider-user2是轮询，*/
    @GetMapping("/test")
    public Map<String, ServiceInstance> test() {
        Map<String, ServiceInstance> map = new HashMap<>(2);
        ServiceInstance serviceInstance1 = this.loadBalancerClient.choose("user-provider-1");
        System.out.println(serviceInstance1.getUri() + ": " + serviceInstance1.getHost() + ": " + serviceInstance1.getServiceId());
        ServiceInstance serviceInstance2 = this.loadBalancerClient.choose("user-provider-2");
        System.out.println(serviceInstance2.getUri() + ": " + serviceInstance2.getHost() + ": " + serviceInstance2.getServiceId());
        map.put("serviceInstance-1", serviceInstance1);
        map.put("serviceInstance-2", serviceInstance2);
        return map;
    }
}
